import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MenuService } from '../../core/services/menu.service';
import { RepairService } from './repair.service';
import { MainFormatService } from '../../core//services/main-format.service';
import { CoreMessageService } from '../../core/services/core-message.service';
import { StyleService } from '../../core/';
import { MapService } from '../../core';
import * as wellknown from 'wellknown';
import { Subscription } from 'rxjs';




@Component({
  selector: 'app-repair',
  templateUrl: './repair.component.html',
  styleUrls: ['./repair.component.scss']
})
export class RepairComponent implements OnInit, OnDestroy {
  constructor(
    private router: Router,
    private menuService: MenuService,
    private repairService: RepairService,
    private styleMapService: StyleService,
    private apboxMapService: MapService,
    private formatdata: MainFormatService,
    private coreMessageService: CoreMessageService
  ) {
    const urlArr = this.router.url.split("/")
    if (urlArr && urlArr.length > 0) {
      const path = urlArr[urlArr.length - 1];
      this.getSideMenuList(path);
    }
  }
  showPanelSubscription: Subscription;
  // 最大最小深度
  minDepthValue = 0;
  maxDepthValue = 0;
  // 最大最小坡度
  minSlopeValue = 0;
  maxSlopeValue = 0;
  // 最大最小管径
  minDiametersValue = 0;
  maxDiametersValue = 0;
  // 默认的radio勾选值
  radioValue = '管点';
  // 切换类型，接口需要的参数格式
  param = {
    type: '管点'
  };
  layersdata = null;
  // 默认侧边栏的状态为false
  sideMenuStatus = null;
  menuList = null;
  mapboxglmap = null;
  isOpen = false;
  // 二级菜单的title
  title = '';
  // 二级菜单是否可见
  visible = false;
  staticType = null;
  configItem = null;
  // 查询表格数据
  tabledata = null;
  // 渲染的柱状图数据
  bardata = null;
  // 渲染的饼图数据
  piedata = null;
  // 对埋深做了特殊照顾
  depthtype = '';
  depthtabledata = null;
  depthbardata = null;
  depthpiedata = null;
  layerList = [];
  searchGeometry = null;
  pbody = {
    layerId: '',
    propertyParams: '',
    geom: ''
  };
  showstaticpanel = false;
  // 少参数的
  bodyparam1 = {
    layer_arr: '',
    geom: ''
  };
  // 多参数的
  bodyparam2 = {
    layer_arr: '',  // 数组转字符串
    geom: '',
    datamin: -10000,
    datamax: 999999
  };
  subscriptations = [];
  // 定义一个对象
  layers = {
    污水管点: 'zpsgx_wsgd_pt',
    雨水管点: 'zpsgx_ysgd_pt',
    污水管线: 'zpsgx_wsgd_l',
    雨水管线: 'zpsgx_ysgd_l',
  };

  ngOnInit() {
    // 展开侧边栏
    this.isOpen = true;
    // 地图初始化
    this.apboxMapService.init().then((mapboxglmap: any) => {
      this.mapboxglmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded()) {
        this.mapInit(mapboxglmap);
      } else {
        mapboxglmap.on('load', () => {
          this.mapInit(mapboxglmap);
        });
      }
    });


    // 二级菜单初始化
    this.repairService.getLayerListByType(this.param).subscribe(res => {
      this.layersdata = { type: '', layerList: [] };
      this.layersdata.layerList = res.data;
      this.layersdata.type = this.param.type;
    });

    this.showPanelSubscription = this.repairService.closePanelObservable.subscribe(res => {
      this.showstaticpanel = res;
    });

    // 关闭二级查询条件面板以及标识绘制的面板以及查询结果列表面版以及识别出来的详情信息框面板！
    this.subscriptations.push(
      postal.channel('TWOLEVEL_PANEL_CHANNEL').subscribe('twolevel-panel', res => {
        this.close(true);
      }),
      postal.channel('DRAW_TOOL_CHANNEL').subscribe('getGeo', res => {
        // console.log('接受', res);
        if (res) {
          this.searchGeometry = res.features[0].geometry;
        } else {
          this.searchGeometry = null;
        }
      }),
    );
  }

  // 地图初始化
  mapInit(mapboxglmap) {
  }

  // 获取接口数据
  getDataByService(param) {
    switch (this.staticType) {
      case 'pipeDiameter':
        this.maxDiametersValue = this.maxDiametersValue > this.minDiametersValue ? this.maxDiametersValue : 999999;
        Object.assign(this.bodyparam2, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
          datamin: this.minDiametersValue,
          datamax: this.maxDiametersValue
        });
        // 管径的有接口了Content-Type
        this.repairService.getDetailByDiameters(this.bodyparam2).subscribe(res => {
          if (res.code === 1 && res.data.length > 0) {
            this.depthtabledata = this.depthDataToTable(res.data);
            this.depthbardata = this.depthDataToBarChartData(res.data);
          } else {
            // TODO:something
            this.depthtabledata = null;
            this.depthbardata = null;
          }
        });
        break;
      case 'slope':
        this.maxSlopeValue = this.maxSlopeValue > this.minSlopeValue ? this.maxSlopeValue : 999999;
        Object.assign(this.bodyparam2, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
          datamin: this.minSlopeValue,
          datamax: this.maxSlopeValue > this.minSlopeValue ? this.maxSlopeValue : 999999
        });
        // 坡度的有接口了
        this.repairService.getDetailBySlope(this.bodyparam2).subscribe(res => {
          if (res.code === 1 && res.data.length > 0) {
            this.depthtabledata = this.depthDataToTable(res.data);
            this.depthbardata = this.depthDataToBarChartData(res.data);
          } else {
            // TODO:something
            this.depthtabledata = null;
            this.depthbardata = null;
          }
        });
        break;
      case 'buriedDepth':
        this.maxDepthValue = this.maxDepthValue > this.minDepthValue ? this.maxDepthValue : 999999;
        Object.assign(this.bodyparam2, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
          datamin: this.minDepthValue,
          datamax: this.maxDepthValue > this.minDepthValue ? this.maxDepthValue : 999999
        });
        // 埋深的有接口了
        this.repairService.getDetailByDepth(this.bodyparam2).subscribe(res => {
          if (res.code === 1 && res.data.length > 0) {
            this.depthtabledata = this.depthDataToTable(res.data);
            this.depthbardata = this.depthDataToBarChartData(res.data);
          } else {
            // TODO:something
            this.depthtabledata = null;
            this.depthbardata = null;
          }
        });
        break;
      case 'pipeLine':
        Object.assign(this.bodyparam1, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
        });
        // 管线的有接口了
        this.repairService.getDetailByPipeLine(this.bodyparam1).subscribe(res => {
          if (res.code === 1 && res.data.length > 0) {
            this.depthtabledata = this.depthDataToTable(res.data);
            this.depthbardata = this.depthDataToBarChartData(res.data);
          } else {
            // TODO:something
            this.depthtabledata = null;
            this.depthbardata = null;
          }
        });
        break;
      case 'pipePoint':
        Object.assign(this.bodyparam1, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
        });
        // 管点的有接口了
        this.repairService.getDetailByPipePoint(this.bodyparam1).subscribe(res => {
          if (res.code === 1 && res.data.length > 0) {
            this.depthtabledata = this.depthDataToTable(res.data);
            this.depthbardata = this.depthDataToBarChartData(res.data);
          } else {
            // TODO:something
            this.depthtabledata = null;
            this.depthbardata = null;
          }
        });
        break;
      case 'pipeMaterial':
        Object.assign(this.bodyparam1, {
          layer_arr: param.layer_arr.join(','),
          geom: param.sp_geo,
        });
        // 材质的
        this.repairService.getDetailByMaterial(this.bodyparam1).subscribe(res => {
          // TODO:如果报错请查看网页的network是否有数据，这个逻辑可能写的并不是很好！
          if (res.code === 1 && res.data.length > 0) {
            const formmatdata = this.formatData(res.data);
            this.tabledata = this.formatToTableData(formmatdata);
            this.bardata = this.formatdata.fieldAdaptive(formmatdata, [['图层', 'type'], ['材质', 'name'], ['数量', 'value', 'number']]);
            // this.piedata = this.bardata;
          } else {
            this.tabledata = null;
            this.bardata = null;
          }
        });
        break;
      default:
        break;
    }
  }

  changeRadioValue(e) {
    this.param = { type: e };
    this.clearChartData(true);
  }

  clearChartData(e) {
    this.clearAllData();
    // 告诉图层，清空绘制内容
    this.coreMessageService.clearAll();
    this.removeLayers();
    this.showstaticpanel = false;
  }

  staticBySelectLayers(param) {
    this.showstaticpanel = true;
    // 统计之前先清空图层！
    this.removeLayers();
    // 加载图层！
    this.layerList = param.layer_arr; // 把图层给图层列表用于空间查询高亮
    // 添加geo参数
    if (this.searchGeometry) {
      param['sp_geo'] = wellknown.stringify(this.searchGeometry);
    }
    this.exeSearchGoemetry();
    this.getDataByService(param);
  }

  formatDepthData(data) {
    let newdata = [];
    let obj;
    data.forEach(element => {
      if (element.layer && element.length) {
        obj = { 图层: element.layer, 数量: Number(element.cnt), 长度: (element.length.toFixed(2)).toString() };
        newdata.push(obj);
      } else {
        obj = { 图层: element.layer, 数量: Number(element.cnt) };
        newdata.push(obj);
      }
    });
    return newdata;
  }

  depthDataToBarChartData(data) {
    let chartdata = null;
    data = this.formatDepthData(data);  // 处理异常值
    if (this.radioValue === '管点') {
      chartdata = this.formatdata.fieldAdaptive(data, [['图层', 'name'], ['长度', 'type'], ['数量', 'value', 'number']]);
    } else {
      // 把一条数据拆成两条
      chartdata = this.depthDatasplitData(data);
    }
    return chartdata;
  }
  //  (管点、埋深、管线、坡度统计专用函数)---------------格式化为表格数据(依赖了处理异常值函数！)
  depthDataToTable(data) {
    const formmatdata = this.formatDepthData(data);
    return this.formatToTableData(formmatdata);
  }
  //  (管点、埋深、管线、坡度统计专用函数)---------------拆分图表数据一条变成两条
  depthDatasplitData(data) {
    const newbarchartdata = [];

    for (let [ikey, ivalue] of Object.entries(data)) {
      // 第一条记录
      const onedata = { type: '', name: '', value: 0 };
      // 第二条记录
      const twodata = { type: '', name: '', value: 0 };

      for (let [jkey, jvalue] of Object.entries(ivalue)) {
        // 每次处理两条数据。。。
        if (jkey === '图层') {
          onedata.type = jvalue.toString();
          twodata.type = jvalue.toString();
        }
        if (jkey === '数量') {
          onedata.name = jkey;
          onedata.value = Number(jvalue);
        }
        if (jkey === '长度') {
          twodata.name = jkey;
          twodata.value = Number(jvalue);
        }
      }
      newbarchartdata.push(onedata);
      newbarchartdata.push(twodata);
    }
    return newbarchartdata;
  }

  // （按材质统计的专用处理异常值函数）-------------处理异常值
  formatData(data) {
    let newdata = [];
    data.forEach(element => {
      if (element.cz) {
        let obj = { 图层: element.layer, 材质: element.cz, 数量: Number(element.cnt) };
        newdata.push(obj);
      }
    });
    return newdata;
  }

  // 通用函数-----------------------处理成表格数据
  formatToTableData(formmatdata) {
    let objtable = { theader: [], tdata: [] };
    let header = [];
    for (let [key, value] of Object.entries(formmatdata[0])) {
      const obj = { name: key, attr: key };
      header.push(obj);
    }
    objtable.theader = header;
    objtable.tdata = formmatdata;
    return objtable;
  }

  // 清空图层
  removeLayers() {
    // 移除图层
    const layers = this.styleMapService.getLayersIDlist();
    this.apboxMapService.removeLayerByIds(layers);
  }


  exeSearchGoemetry() {
    this.layerList.forEach(element => {
      Object.assign(this.pbody, {
        layerId: this.layers[element],
        propertyParams: [],
        geom: this.searchGeometry ? wellknown.stringify(this.searchGeometry) : ''
      });
      this.repairService.queryGeometry(this.pbody).subscribe(res => {
        switch (element) {
          case '雨水管点':
            this.styleMapService.drawGeo(res.data, 'hightlightrain');
            break;
          case '污水管点':
            this.styleMapService.drawGeo(res.data, 'hightlightsewage');
            break;
          case '雨水管线':
            this.styleMapService.drawGeo(res.data, 'hightlightrain');
            break;
          case '污水管线':
            this.styleMapService.drawGeo(res.data, 'hightlightsewage');
            break;
        }
      });
    });
  }

  // 得到侧边栏信息(这边不负责展开和关闭，代码在侧边栏组件里写着)
  getSideMenuItem(e) {
    this.staticType = e.data.key;
    this.title = e.data.title;
    this.visible = e.visible;
    this.showstaticpanel = false;
    if (this.staticType === 'pipeLine' || this.staticType === 'slope' || this.staticType === 'pipeDiameter') {
      this.radioValue = '管线';
      this.param = { type: '管线' };
    } else {
      this.radioValue = '管点';
      this.param = { type: '管点' };
    }
    // 避免冲突，这里将所有的data清空
    this.clearAllData();
    // 移除图层
    this.removeLayers();
  }

  clearAllData() {
    this.depthbardata = null;
    this.piedata = null;
    this.depthbardata = null;
    this.depthpiedata = null;
    this.bardata = null;
    this.tabledata = null;
    this.maxDepthValue = 0;
    this.maxDiametersValue = 0;
    this.maxSlopeValue = 0;
    this.minDepthValue = 0;
    this.minDiametersValue = 0;
    this.minSlopeValue = 0;
    this.searchGeometry = null;
  }


  getSideMenuList(id) {
    this.menuService.getSideMenuList(id).subscribe(res => {
      this.menuList = res;
    });
  }


  getConfigItem(configs, key) {
    console.log(configs, key);
    let item = null;
    item = configs[key];
    return item;
  }

  ngOnDestroy() {
    // 侧边栏关闭
    this.isOpen = false;
    this.visible = false;
    this.showstaticpanel = false;
    this.searchGeometry = null;
    this.clearChartData(true);
    // 取消订阅
    this.subscriptations.forEach(element => {
      element.unsubscribe();
    });
    this.showPanelSubscription.unsubscribe();
  }

  // （关闭二级详情菜单的）
  close(e) {
    this.visible = false;
    this.showstaticpanel = false;
    this.searchGeometry = null;
    this.clearChartData(true);
    this.staticType = null;
    // 告知侧边栏，我这边要置空（只是用这个引发了change事件。这是个雷）
    this.sideMenuStatus = { visible: false };
  }

}